package DAO.Servlet;

import DAO.JavaBean.CustomerBean;
import DAO.JavaDAO.CustomerDAO;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(value = "/action")
public class ActionServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        CustomerDAO customerDAO = new CustomerDAO();
        System.out.println("111");
        try {
            if (customerDAO.deleteCustomer(request.getParameter("id"))) {
                response.sendRedirect("DAO/showCustomer.jsp");
            } else {
                response.sendRedirect("jsp/errorPage.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            customerDAO.destoryConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        CustomerBean customerBean = new CustomerBean(
                req.getParameter("custName"), req.getParameter("email"), req.getParameter("phone")
        );
        CustomerDAO customerDAO = new CustomerDAO();
        try {
            if (customerDAO.update(customerBean))
                resp.sendRedirect("DAO/showCustomer.jsp");
            else resp.sendRedirect("jsp/errorPage.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            customerDAO.destoryConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
